package com.flashcash.kotlin.face

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Base64
import com.flashcash.solu.R
import com.flashcash.solu.common.FieldParams
import com.oliveapp.face.livenessdetectorsdk.livenessdetector.datatype.LivenessDetectionFrames
import com.oliveapp.face.livenessdetectorsdk.livenessdetector.datatype.OliveappFaceInfo
import com.oliveapp.libcommon.utility.LogUtil
import com.oliveapp.liveness.sample.liveness.view_controller.LivenessDetectionMainActivity

/**
 * Created by XLEO on 2018/4/20.
 */
class FaceDetectActivity : LivenessDetectionMainActivity() {
    val TAG = FaceDetectActivity::class.java.simpleName

    /**
     * =====================启动算法===============
     */
    override fun onInitializeSucc() {
        super.onInitializeSucc()
        super.startVerification()
    }

    override fun onInitializeFail(e: Throwable) {
        super.onInitializeFail(e)
        LogUtil.e(TAG, "无法初始化活体检测...", e)
        setResult(Activity.RESULT_CANCELED, createFailedMsgIntent(R.string.initialize_fail))
        finish()
    }

    /**===================================活体检测算法的回调==================================**/
    /**
     * 活体检测成功的回调，同时获取大礼包
     * 成功回调的接口在1.7.a_hotfix被拆成了2步，不再使用该接口
     *
     * @param livenessDetectionFrames 活体检测抓取的图片
     * @param faceInfo                捕获到的人脸信息
     */
    override fun onLivenessSuccess(livenessDetectionFrames: LivenessDetectionFrames, faceInfo: OliveappFaceInfo) {
        super.onLivenessSuccess(livenessDetectionFrames, faceInfo)

        runOnUiThread {
            if (livenessDetectionFrames == null || livenessDetectionFrames!!.verificationData == null) {
                setResult(Activity.RESULT_CANCELED, createFailedMsgIntent(R.string.faceid_detect_fail))
                finish()
            } else {
                DeltaHolder.instance.delta = Base64.encodeToString(livenessDetectionFrames.verificationData, Base64.NO_WRAP) // 保存大礼包
                setResult(Activity.RESULT_OK)
                finish()
            }
        }
    }

    /**
     * 活检阶段失败
     */
    override fun onLivenessFail(result: Int, livenessDetectionFrames: LivenessDetectionFrames) {
        super.onLivenessFail(result, livenessDetectionFrames)

        runOnUiThread {
            setResult(Activity.RESULT_CANCELED, createFailedMsgIntent(R.string.faceid_detect_fail))
            finish()
        }
    }

    /**
     * 每一帧结果的回调方法
     */
    override fun onFrameDetected(currentActionType: Int, actionState: Int, sessionState: Int, remainingTimeoutMilliSecond: Int, faceInfo: OliveappFaceInfo?, errorCodeOfInAction: ArrayList<Int>?) {
        super.onFrameDetected(currentActionType, actionState, sessionState, remainingTimeoutMilliSecond, faceInfo, errorCodeOfInAction)

        if (remainingTimeoutMilliSecond / 1000 <= 0) { // 活体检测超时
            runOnUiThread {
                setResult(Activity.RESULT_CANCELED, createFailedMsgIntent(R.string.faceid_detect_fail))
                finish()
            }
        }
    }

    private fun createFailedMsgIntent(strId: Int): Intent {
        return createFailedMsgIntent(this.getString(strId))
    }

    private fun createFailedMsgIntent(str: String?): Intent {
        val intent = Intent()
        val bundle = Bundle()
        bundle.putString(FieldParams.LivenessExtras.FAILED_MSG, str ?: "")
        intent.putExtras(bundle)
        return intent
    }
}

class DeltaHolder {
    var delta: String? = null

    companion object {
        val instance = DeltaHolder()
    }
}